import axios from 'axios'
import $ from 'jquery'

const DevBaseUrl = 'https://yn.12348.laway.cn'
// const DevBaseUrl = 'http://localhost:8888'
const ProdBashUrl = 'https://yn.12348.laway.cn'

let config = {
  baseURL: process.env.NODE_ENV !== 'production' ? DevBaseUrl : ProdBashUrl, // 配置API接口地址
  headers: { Authorization: localStorage.code ? 'ZD ' + localStorage.code : '' }
  // timeout: 15000
}

axios.interceptors.request.use(config => {
  config.headers.Authorization = localStorage.code
    ? 'ZD ' + localStorage.code
    : ''
  return config
})

let request = axios.create(config)
export const requests = request

export function get(url, _this, loader = '') {
  // url = url.includes('http://') ? url : api + url
  if (_this) {
    _this.$loading.show(loader)
  }
  return request
    .get(url)
    .then(res => {
      if (_this) {
        _this.$loading.hide()
      }
      if (res.status !== 200) {
        throw new Error(res.url + ' ' + res.status + ' ' + res.statusText)
      }
      return res.data
    })
    .catch(err => {
      if (_this) {
        _this.$loading.hide()
      }
      throw err
    })
}

export function post(url, query, _this, loader = '') {
  if (_this) {
    _this.$loading.show(loader)
  }
  return request
    .post(url, query)
    .then(res => {
      if (_this) {
        _this.$loading.hide()
      }
      if (res.status !== 200) {
        throw new Error(res.url + ' ' + res.status + ' ' + res.statusText)
      }
      return res.data
    })
    .catch(err => {
      if (_this) {
        _this.$loading.hide()
      }
      throw err
    })
}

export function asyncJquery(
  url,
  type,
  data,
  success = function(data, textStatus, jqXHR) {
    console.log(data)
  },
  async = false,
  timeout = 3000,
  error = function(xhr, textStatus) {
    console.log(textStatus)
  }
) {
  $.ajax({
    url,
    type, // GET
    async, // 或false,是否异步
    data,
    timeout, // 超时时间
    dataType: 'json', // 返回的数据格式：
    success,
    error
  })
}
